//
// Created by zyh on 2022/10/19
//

#include <string.h>
#include "util/date.h"
#include "common/log/log.h"
#include <sstream>
#include "rc.h"
#include <cstdint>

void date2string(int date, std::ostream &os)
{
  int year = 0;
  int month = 0;
  int day = 0;
  year = date / 10000;
  month = date % 10000 / 100;
  day = date % 100;
  os << year << "-";
  if (month < 10) {
    os << "0";
  }
  os << month << "-";
  if (day < 10) {
    os << "0";
  }
  os << day;
}

RC str2date(char *date_str, int32_t &date)
{
  RC rc;
  int year = 0;
  int month = 0;
  int day = 0;
  int ret = sscanf(date_str, "%d-%d-%d", &year, &month, &day);
  if (ret != 3) {
    rc = RC::INVALID_ARGUMENT;
    return rc;
  }
  if ((year < 1900 || year > 9999) || (month <= 0 || month > 12) || (day <= 0 || day > 31)) {
    rc = RC::INVALID_ARGUMENT;
    return rc;
  }
  int day_max[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  if (day > day_max[month - 1]) {
    rc = RC::INVALID_ARGUMENT;
    return rc;
  }
  if (!is_luna_year(year) && month == 2 && day > 28) {
    rc = RC::INVALID_ARGUMENT;
    return rc;
  }
  int32_t value = year * 10000 + month * 100 + day;
  date = value;
  return RC::SUCCESS;
}

bool is_luna_year(int year)
{
  return (year % 4 == 0 || year % 400 == 0) && year % 100 != 0;
}
